package wendyeq.iweb.blog.service.impl;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import wendyeq.iweb.blog.dao.IArticleDAO;
import wendyeq.iweb.blog.dao.ITagsDAO;
import wendyeq.iweb.blog.pojo.Article;
import wendyeq.iweb.blog.pojo.Tags;
import wendyeq.iweb.blog.service.ITagsService;

@Service("tagsServiceImpl")
public class TagsServiceImpl implements ITagsService{
	private static final Logger logger = Logger.getLogger(TagsServiceImpl.class);
	
	@Resource(name="tagsDAO")
	private ITagsDAO tagsDAO;
	
	@Resource(name="articleDAO")
	private IArticleDAO articleDAO;
	
	@Override
	public boolean save(Tags tag) {
		if(this.tagsDAO.findByTag(tag.getName())==null) {
			logger.warn("TagsService -- do insert!");
			return this.tagsDAO.saveOrUpdate(tag);
		} else{
			logger.warn("TagsService -- do insert false!");
			return false;
		}
	}
	@Override
	public boolean modify(String oldName, String newName) {
		//this.articleService.updateTags(oldName, newName);
		Tags t = this.tagsDAO.findByTag(oldName);
		Set<String> aids = t.getArticles();
		for (String aid : aids){
			Article a = this.articleDAO.findById(aid);
			a.getTags().remove(oldName);
			a.getTags().add(newName);
			this.articleDAO.saveOrUpdate(a);
		}
		Tags tag = this.tagsDAO.findByTag(oldName);
		tag.setName(newName);
		return this.tagsDAO.saveOrUpdate(tag);
	}
	
	public boolean delete(String id) {
		Tags tag = this.tagsDAO.findById(id);
		Set<String> aids = tag.getArticles();
		for (String aid : aids){
			Article a = this.articleDAO.findById(aid);
			a.getTags().remove(tag.getName());
			this.articleDAO.saveOrUpdate(a);
		}
		return this.tagsDAO.delete(id);
	}
	
	@Override
	public Tags findById(String id) {
		return this.tagsDAO.findById(id);
	}
	
	@Override
	public Tags findByTag(String t) {
		return this.tagsDAO.findByTag(t);
	}
	
	@Override
	public List<Tags> findByPage(int min, int max) {
		// TODO Auto-generated method stub
		return this.tagsDAO.findByPage(min, max);
	}
	@Override
	public List<Tags> findAll() {
		return this.tagsDAO.findAll();
	}


}
